package org.clockwise.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


public class T2SConvertor {
	
	public static LinkedHashMap<String, String> t2sDict;
//	public static LinkedHashMap<String, String> s2tDict;
	
	public static boolean initConvertor() {
		String source = "trad_to_simp_characters.txt";
		t2sDict = new LinkedHashMap<String, String>();
//		s2tDict = new LinkedHashMap<String, String>();
		
		try {
			BufferedReader reader = new BufferedReader(new FileReader(source));
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				String[] pair = temp.split("\t");
				if (pair.length == 2) {
					t2sDict.put(pair[0], pair[1]);
//					s2tDict.put(pair[1], pair[0]);
				}
			}
		//	System.out.println("" + dict.size() + " characters are read");
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Failed to init the dict!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Failed to read the dictionary file!");
		}
		return false;
	}
	
	private static String convertCharT2S(String tradition) {
		if (t2sDict.containsKey(tradition)) {
			return t2sDict.get(tradition);
		}
		else {
			return tradition;
		}
	}
	
	public static String convertStrT2S(String input) {
		if (t2sDict == null) {
			T2SConvertor.initConvertor();
		}
		String output = "";
		for (int i = 0; i < input.length(); i++) {
			output += convertCharT2S(input.substring(i, i + 1));
		}
		return output;
	}
	
	/** Through some simple tests, it seems that each Chinese charactor is made of
	 * three negative bytes, while other common English charactor is made of one
	 * positive byte representing its ascii code value.
	 * The encoding is UTF-8
	 * 
	 * @param single
	 * @return
	 */
	
	
	public static boolean isChinese(String single) {
		if (single.length() == 0) return false;
		byte[] b = single.getBytes();
		if ((b[0] & 0x80) != 0) {
			return true;
		}
		else return false;
	}
	
	public static String[] seperateEnCh(String input) {
		List<String> result = new ArrayList<String>();
		
		return null;
	}
	
	public static void convertFileT2S(String file) {
		MyFileReader mfr = new MyFileReader(file);
		ArrayList<String> content = new ArrayList<String>();
		String temp = null;
		while ((temp = mfr.getNextLine()) != null) {
			content.add(convertStrT2S(temp));
		}
		mfr.close();
		MyFileWriter mfw = new MyFileWriter(file, true);
		Iterator<String> iter = content.iterator();
		while (iter.hasNext()) {
			mfw.write(iter.next() + "\n");
		}
		mfw.close();
	}
	
	
}






